package com.gpStudy.distributed.buffer;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class BufferDemo {
    
    public static void main(String[] args){
        try {

            // 文件IO处理
            FileInputStream fin = new FileInputStream("D://test.txt");

            // 创建文件的操作管道，内部实现是打开了一个管道
            FileChannel fc = fin.getChannel();

            // 分配缓冲区，分配一个 大小为10的byte数组
            ByteBuffer buffer = ByteBuffer.allocate(1024);

            output("初始化", buffer);

            fc.read(buffer);
            output("调用read()",buffer);

            buffer.flip();
            output("调用 flip()",buffer);

            while(buffer.remaining()>0){
                byte b = buffer.get();
            }
            output("调用 get()",buffer);

            buffer.clear();
            output("调用 clear()", buffer);

            fin.close();


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void output(String step, ByteBuffer buffer) {

        System.out.println(step + ":");
        //容量，数组大小
        System.out.println("capacity:" + buffer.capacity() + ",");
        //当前操作数据所在的位置，也可以叫做游标
        System.out.println("position:" + buffer.position() + ",");
        //锁定值，flip，数据操作范围索引只能在position - limit 之间
        System.out.println("limit:" + buffer.limit() + ",");
        System.out.println("");

    }
}
